package com.yigo.framework.http;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenzl
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        List<String> errors = new ArrayList<>();
        if (bindingResult.hasErrors()) {
            errors.addAll(bindingResult.getAllErrors().stream()
                    .map(x -> x.getDefaultMessage()).collect(Collectors.toList()));
        }
        return R.fail(RCodeEnum.PARAMS_VALID_ERROR, String.join(";", errors));
    }

    @ExceptionHandler(BException.class)
    public R handleBException(BException e) {
        e.printStackTrace();
        return R.fail(e);
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        e.printStackTrace();
        return R.fail(RCodeEnum.FAIL, e.getMessage());
    }
}
